<script setup>
  import 'leaflet/dist/leaflet.css'
  // Import a static copy of the css; because for some reason importing it from npm pkg is buggy
  import '/src/css/leaflet-markercluster-style.css'

  import L from 'leaflet'
  import {
    LControlLayers,
    LFeatureGroup,
    LIcon,
    LMap,
    LMarker,
    LPopup,
    LTileLayer,
  } from '@vue-leaflet/vue-leaflet'

  import { LMarkerClusterGroup } from 'vue-leaflet-markercluster'

  import { ref, watchEffect } from 'vue'

  import IconSpan from '@/components/IconSpan.vue'
  import { useConstStore } from '@/stores/const'
  import http from '@/helpers/http'
  import Icon from '@/components/Icon.vue'
  import TextWithBr from '@/components/TextWithBr.vue'

  const loading = ref(true)
  const endiConfig = ref({})

  const mapBounds = ref(new L.Bounds())
  const constStore = useConstStore()
  const companiesGeoData = ref()
  const extraPlacesGeoData = ref()
  // Track current displayed popup to allow lazyload of logos.
  const currentCompanyId = ref()
  
  const props = defineProps({
    companiesUrl: {type: String, required: true},
    extraPlacesUrl: {type: String, required: true},
  })


  const showLayerInMap = (layer) => {
    const bounds = layer.getBounds()
    if (mapBounds.value.isValid()) {
      mapBounds.value.extend(bounds)
    } else {
      mapBounds.value = bounds
    }
  }

  endiConfig.value = await constStore.loadConst('config')

  await Promise.allSettled([
      http.get(props.companiesUrl),
      http.get(props.extraPlacesUrl)
  ]).then(([companies_response, extraplaces_response]) => {
      if (companies_response.status == 'fulfilled' && companies_response.value) {
          companiesGeoData.value = companies_response.value
      }
      if (extraplaces_response.status == 'fulfilled' && extraplaces_response.value) {
          extraPlacesGeoData.value = extraplaces_response.value
      }
      loading.value = false
  })
  

  // Update companies layer if URL changes
  watchEffect(async () => {
      companiesGeoData.value = await http.get(props.companiesUrl)
    },
  )

</script>

<template>
  <div v-if='loading'>Chargement…</div>
  <div style='width: 100%; height: 70vh' class='toggle'>
    <l-map ref='map' :center='[47.21297, -1.55104]' :zoom='18' :bounds='mapBounds'>
      <l-control-layers position="topright" :collapsed='false'></l-control-layers>
      <l-tile-layer
        :url='endiConfig.leaflet_layer_url'
        attribution='&copy; Contributeur·ices <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a>'
      />

      <l-feature-group
        name='Lieux ressources' key='places'  layer-type='overlay'
        @ready='showLayerInMap'
      >
        <l-marker
          v-if='extraPlacesGeoData'
          v-for='feature in extraPlacesGeoData.features'
          :lat-lng='L.GeoJSON.coordsToLatLng(feature.geometry.coordinates)'
        >
          <l-icon>
            <IconSpan name='location-star' css-class='map_location favourite' :alt='feature.properties.name'/>
          </l-icon>
          <l-popup>
            <div>
              <p>
                <strong>{{ feature.properties.name }}</strong>
              </p>
              <p v-if='feature.properties.description'>
                <TextWithBr :text='feature.properties.description' />
              </p>
              <ul class='contacts'>
                <li v-if='feature.properties.website'>
                    <a :href='feature.properties.website'>
                      <IconSpan name='globe' alt='Site web' title='Site web'/>
                      {{ feature.properties.website }}
                    </a>
                </li>
                <li v-if='feature.properties.contact'>
                  <IconSpan name='user'  alt='' />
                  Contact : {{ feature.properties.contact }}
                </li>
              </ul>
            </div>
          </l-popup>
        </l-marker>
      </l-feature-group>

      <l-marker-cluster-group
        name='Enseignes et entrepreneur·euses' key='companies' layer-type='overlay'
        @ready='showLayerInMap'
      >
        <l-marker
          v-for='feature in companiesGeoData.features'
          :lat-lng='L.GeoJSON.coordsToLatLng(feature.geometry.coordinates)'
          @popupopen='currentCompanyId = feature.properties.id'
        >
          <l-icon>
            <IconSpan name='location-dot' css-class='map_location' :alt='feature.properties.name' />
          </l-icon>
            <l-popup>
              <div>
                <p>
                  <strong>{{ feature.properties.name }}</strong>
                </p>
                <p v-if='feature.properties.goal'><em>{{ feature.properties.goal}}</em></p>
                <p v-if='feature.properties.activities_labels.length > 0'>
                  {{ feature.properties.activities_labels.join(', ') }}
                </p>
                <ul class="contacts">
                  <li v-if='feature.properties.phone'>
                    <a :href='`tel:${feature.properties.phone}`'>
                      <IconSpan name='phone' alt="Téléphone" title="Téléphone" />
                      {{ feature.properties.phone }}
                    </a>
                  </li>
                  <li v-if='feature.properties.mobile'>
                    <a :href='`tel:${feature.properties.mobile}`'>
                      <IconSpan name='mobile-alt' title='Téléphone portable' alt="Téléphone portable" />
                      {{ feature.properties.mobile }}
                    </a>
                  </li>
                  <li v-if='feature.properties.email'>
                    <a :href='`mailto:${feature.properties.email}`'>
                      <IconSpan name='envelope' title='E-mail' alt="E-mail" />
                      {{ feature.properties.email }}
                    </a>
                  </li>
                </ul>
                <ul class='users'>

                  <li v-for='user in feature.properties.users_gallery'>
                    <!--
                         Renders only if the API gives us a logo
                         + lazy-loading of logos to avoid mass-loading them on page startup.
                    -->
                    <span v-if='user.logo_url  && currentCompanyId === feature.properties.id' class='user_avatar photo'>
                      <img :src='user.logo_url' :alt='user.fullname' width='48' height='48'/>
                    </span>
                    <span v-else class='user_avatar'>
                      <Icon name='user' />
                    </span>
                    <span>
                      {{ user.fullname }}
                    </span>
                  </li>
                </ul>
              </div>
          </l-popup>
        </l-marker>
      </l-marker-cluster-group>
    </l-map>
  </div>


</template>
